#include"queue.h"

void QueueInit(Queue* pq){
	assert(pq);
	pq->front = pq->rear = NULL;
	pq->size = 0;
}

void QueueDestroy(Queue* pq) {
	assert(pq);
	QueueNode* cur = pq->front;
	while (cur) {
		QueueNode* tail = cur->next;
		free(cur);
		cur = tail;
	}
	pq->front = pq->rear = NULL;
	pq->size = 0;
}

bool QueueIsEmpty(Queue* pq) {
	assert(pq);
	return pq->size == 0;
}

int Queuesize(Queue* pq) {
	assert(pq);
	return pq->size;
}

void QueuePush(Queue* pq,QDataType x) {
	assert(pq);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL) {
		perror("malloc false");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->front == NULL) {
		pq->front = pq->rear = newnode;
	}
	else {
		pq->rear->next = newnode;
		pq->rear = newnode;
	}
	pq->size++;
}

void QueuePop(Queue* pq) {
	assert(pq);
	assert(!QueueIsEmpty(pq));
	if (pq->front == pq->rear) {
		free(pq->front);
		pq->front = pq->rear = NULL;
	}
	else {
		QueueNode* tail = pq->front->next;
		free(pq->front);
		pq->front = tail;
	}
	pq->size--;
}

QDataType GetQueueFront(Queue* pq) {
	assert(pq);
	assert(!QueueIsEmpty(pq));
	return pq->front->data;
}

QDataType GetQueueRear(Queue* pq) {
	assert(pq);
	assert(!QueueIsEmpty(pq));
	return pq->rear->data;
}